﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRC.Utilities.Entities;
using System.Net;

namespace IRC.Utilities
{
    public static class ConfigFileParser
    {
        /// <summary>
        /// Loads the node configuration from path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>List of node configuration objects.</returns>
        public static List<NodeConfiguration> LoadConfigurationFromPath(string path)
        {
            try
            {
                string configuration = System.IO.File.ReadAllText(path);
                string[] lines = configuration.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

                List<NodeConfiguration> nodeConfigurations = new List<NodeConfiguration>();

                foreach (string line in lines)
                {
                    string[] parameters = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    nodeConfigurations.Add(new NodeConfiguration()
                    {
                        NodeID = int.Parse(parameters[0]),
                        Hostname = parameters[1],
                        LocalPort = int.Parse(parameters[2]),
                        RoutingPort = int.Parse(parameters[3]),
                        ServerPort = int.Parse(parameters[4])
                    });
                }

                return nodeConfigurations;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        public static IPAddress DNSLookup(string hostNameOrAddress)
        {
            IPAddress[] ips = Dns.GetHostAddresses(hostNameOrAddress);

            if (ips.Length == 0)
                throw new Exception("Host not found");
            else
                return ips[0];
        }  
    }
}
